package com.sky.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.dto.PageDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealDishMapper;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavoMapper;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品和对应的口味
     *
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void saveWithFlavor(DishDTO dishDTO) {
        // 转换为 entity 数据表对应的对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        // 向菜品表插入数据
        dishMapper.insert(dish);
        // 获取 insert 语句生成的主键
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        // 为 DishFlavor 设置Dish的id值
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            // 向口味表中插入 N 条数据
            dishFlavorService.saveBatch(flavors);
        }

    }

    /**
     * 菜品分页查询
     *
     * @param queryDTO
     * @return
     */
    @Override
    public PageDTO<DishVO> pageQuery(DishPageQueryDTO queryDTO) {
        // 设置分页条件
        Page<DishVO> page = Page.of(queryDTO.getPage(), queryDTO.getPageSize());
        // 设置查询条件
        dishMapper.pageQuery(page, queryDTO);
        // 返回查询结果
        long total = page.getTotal();
        List<DishVO> records = page.getRecords();

        return new PageDTO<DishVO>(total, records);
    }

    /**
     * 菜品批量删除
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void deleteBatch(List<Long> ids) {
        // 判断商品的起售状态
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                // 存在菜品处于起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        // 判断商品是否与套餐有关联
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds == null || !setmealIds.isEmpty()) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        // 删除菜品
        dishMapper.deleteBatchIds(ids);
        // 删除菜品关联的口味数据
        dishFlavoMapper.deleteBatchIds(ids);
    }

    /**
     * 根据id查询菜品和口味数据
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        // 根据id查询菜品数据
        Dish dish = dishMapper.selectById(id);
        // 查询 Falvor 数据
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavors = dishFlavoMapper.selectList(wrapper);

        // 封装 DishVO 对象
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        // 修改菜品
        dishMapper.update(dish);
        // 删除原有口味
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dishDTO.getId());
        dishFlavoMapper.delete(wrapper);
        // 插入新口味数据
        dishFlavorService.saveBatch(dishDTO.getFlavors());
    }

    /**
     * 修改菜品状态
     * @param status
     * @param id
     */
    @Override
    public void StartOrStop(Integer status, long id) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> queryDishByCategoryId(long categoryId) {
        // 查询菜品
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, categoryId)
                .eq(Dish::getStatus, StatusConstant.ENABLE);
        List<Dish> dishes = dishMapper.selectList(wrapper);

        // 转换为CategoryDTO对象
        return BeanUtil.copyToList(dishes, DishVO.class);
    }

    /**
     * 删除 redis 菜品数据
     * @param pattern
     */
    @Override
    public void cleanRedisCache(String pattern) {
        // 获取所有符合指定模式的key
        Set keys = redisTemplate.keys(pattern);
        Long result = redisTemplate.delete(keys);
    }
}
